package com.tedu.element.map;

import com.tedu.element.ElementObj;
import com.tedu.manager.GameLoad;

import java.awt.*;

public class GameMap {
    private MapObj[][] mapGrid;  // 二维地图网格
    private MapObj[][] mapFloor;    // 二维地板
    private final int gridWidth;  // 地图宽度(格子数)
    private final int gridHeight; // 地图高度(格子数)

    public GameMap(int width, int height, int floorTileCode) {
        this.gridWidth = width;
        this.gridHeight = height;
        this.mapGrid = new MapObj[height][width];
        this.mapFloor = new MapObj[height][width];
        init(floorTileCode);
    }

    private void init(int floorTileCode) {
        for (int gridY = 0; gridY < gridHeight; gridY++) {
            for (int gridX = 0; gridX < gridWidth; gridX++) {
                mapFloor[gridY][gridX] = createMapObj(gridX, gridY, floorTileCode);
            }
        }
    }

    /**
     * 获取指定位置的格子
     */
    public MapObj getTile(int gridX, int gridY) {
        return isValidPosition(gridX, gridY) ? mapGrid[gridY][gridX] : null;
    }

    /**
     * 设置指定位置的物体
     */
    public void setTile(int gridX, int gridY, int tileCode) {
        if (isValidPosition(gridX, gridY)) {
            mapGrid[gridY][gridX] = createMapObj(gridX, gridY, tileCode);
        }
    }

    /**
     * 检查坐标是否合法
     */
    private boolean isValidPosition(int gridX, int gridY) {
        return gridX >= 0 && gridX < gridWidth && gridY >= 0 && gridY < gridHeight;
    }

    /**
     * 创建 MapObj 对象
     */
    private MapObj createMapObj(int gridX, int gridY, int tileCode) {
        ElementObj obj = GameLoad.getObj("mapObj");
        assert obj != null;
        return (MapObj) obj.createElement(gridX + "," + gridY + "," + tileCode);
    }

    /**
     * 绘制地图地板
     */
    public void showMapFloor(Graphics g) {
        for (int gridY = 0; gridY < gridHeight; gridY++) {
            for (int gridX = 0; gridX < gridWidth; gridX++) {
                mapFloor[gridY][gridX].showElement(g);
            }
        }
    }

    /**
     * 绘制地图地板上层物品
     */
    public void showMapGrid(Graphics g) {
        for (int gridY = 0; gridY < gridHeight; gridY++) {
            for (int gridX = 0; gridX < gridWidth; gridX++) {
                if (!mapGrid[gridY][gridX].isLive()) {
                    mapGrid[gridY][gridX].setType(TileType.EMPTY);
                }
                mapGrid[gridY][gridX].showElement(g);
            }
        }
    }

    public int getGridWidth() {
        return gridWidth;
    }

    public int getGridHeight() {
        return gridHeight;
    }
}
